<?php
namespace App\Ext\Common;

class Page
{
    /**
     *
     * 显示分页
     *
     * @param $total 记录总数
     * @param $page 当前页面
     * @param $limit 每页显示条数
     * @param null $url 页面地址或路由别名
     * @param null $param 页面传参
     * @return array
     *
     * example:
     * Page::display(100, 2, 10, 'index', ['id'=>1]);
     */
    public static function display($total, $page, $limit, $url, $param = null)
    {
        $result = array();
        if ($total < 1) return $result;
        if (!$page) $page = 1;
        //分页总数
        $result['total_page'] = (int)ceil($total / $limit);
        $result['total_page'] = ($result['total_page'] < 1) ? 1 : $result['total_page'];
        //上页链接
        $param['page'] = $page > 1 ? $page - 1 : 1;
        $result['previous'] = route($url, $param);
        //下页链接
        $param['page'] = $page < $result['total_page'] ? $page + 1 : $result['total_page'];
        $result['next'] = route($url, $param);
        //首页链接
        $param['page'] = 1;
        $result['first'] = route($url, $param);
        //尾页链接
        $param['page'] = $result['total_page'];
        $result['last'] = route($url, $param);
        //计算按步长分页
        $result['step'] = [];
        $step = 5;  //步长
        $start = $page - ($step - 1) / 2;
        if ($start < 1) {
            $start = 1;
            $end = ($step > $result['total_page']) ? $result['total_page'] : $step;
        } else {
            $end = $start + $step - 1;
            if ($end > $result['total_page']) {
                $offset = $start - ($end - $result['total_page']);
                $start = ($offset < 1) ? 1 : $offset;
                $end = $result['total_page'];
            }
        }
        $temp = array();
        for ($i = $start; $i <= $end; $i++) $temp[] = intval($i);
        foreach ($temp as $key => $value) {
            $param['page'] = $value;
            $result['step'][$value] = route($url, $param);
        }
        return $result;
    }
}